package org.javaboy.swagger2.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.javaboy.swagger2.bean.User;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.*;

/**
 * @Author 江南一点雨
 * @Site www.javaboy.org 2019-06-05 9:38
 */
@RestController
@Api(tags = "测试接口")
@RequestMapping("test")
public class TestController {

    @ApiOperation("根据id查询用户")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99")
    @GetMapping("getUserById")
    public User getUserById(int id) {
        User user = new User();
        user.setId(id);
        user.setUsername("zhang san "+id);
        user.setAddress("test address "+id);
        user.setAge(18+id);
        user.setEmail("test@163.com");
        user.setGender(1);

        return user;
    }

    @ApiOperation("根据id更新用户名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99"),
            @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "javaboy")
    })
    @PutMapping("updateUsernameById")
    public User updateUsernameById(String username, int id) {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        return user;
    }

    @PostMapping("addUser")
    @ApiOperation("添加用户")
    public User addUser(@RequestBody User user) {
        return user;
    }

    @DeleteMapping("deleteUserById/{id}")
    @ApiOperation("根据id 删除用户")
    public void deleteUserById(@PathVariable Long id) {

    }

    @GetMapping("hello")
    public String hello(String name) {
        return "hello " + name + " !";
    }

    @GetMapping("readLocalFile")
    public String readLocalFile(String fileName) throws IOException {

        String file = "register.html";
        ClassPathResource classPathResource = new ClassPathResource(file);
        InputStream inputStream = classPathResource.getInputStream();
        String content=convertStream2String(inputStream);

        return "file content: " + content;
    }

    public String convertStream2String(InputStream inputStream){
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            try {
                inputStream.close();
                bufferedReader.close();
            } catch (Exception e1) {
            }
        }
        return null;
    }

}
